﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Akso.Authorization;
using Akso.Entities;
using Akso.Invoices.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
using Abp.Linq.Extensions;
using Abp.AutoMapper;
using System.Diagnostics;

namespace Akso.Invoices
{
    [AbpAuthorize(AppPermissions.Pages_FinanceModule_Invoices)]
    public class InvoiceAppService: AbpZeroTemplateAppServiceBase, IInvoiceAppService
    {
        private readonly IRepository<Invoice, Guid> _invoicesRepository;

        public InvoiceAppService(IRepository<Invoice, Guid> invoicesRepository)
        {
            _invoicesRepository = invoicesRepository;
        }

        #region 查询数据
        /// <summary>
        /// 根据输入条件进行数据查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private IQueryable<Invoice> getQuery(GetInvoicesInput input)
        {
            var query = _invoicesRepository.GetAll()
                .WhereIf(
                    !input.Filter.IsNullOrWhiteSpace(),
                    t =>
                        t.InvoiceStartCode.Contains(input.Filter) ||
                        t.Remark.Contains(input.Filter)
                );
            return query;
        }
        public async Task<ListResultDto<InvoiceListDto>> GetObjects(GetInvoicesInput input)
        {
            var query = getQuery(input);
            var dataCount = await query.CountAsync();
            var data = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();

            return new PagedResultDto<InvoiceListDto>(
                dataCount,
                data.MapTo<List<InvoiceListDto>>()
                );
        }
        #endregion

        #region 新增、编辑对象，带权限检查
        /// <summary>
        /// 新增、编辑对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_FinanceModule_Invoices_Create, AppPermissions.Pages_FinanceModule_Invoices_Edit)]
        public async Task<Invoice> CreateOrUpdateObject(CreateOrUpdateInvoiceInput input)
        {
            if (input.Invoice.Id.HasValue)
            {
                return await UpdateObject(input);
            }
            else
            {
                return await CreateObject(input);
            }
        }

        /// <summary>
        /// 新增对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_FinanceModule_Invoices_Create)]
        protected virtual async Task<Invoice> CreateObject(CreateOrUpdateInvoiceInput input)
        {
            var o = input.Invoice.MapTo<Invoice>();
            
            return await _invoicesRepository.InsertAsync(o);
        }
        /// <summary>
        /// 编辑对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_FinanceModule_Invoices_Edit)]
        protected virtual async Task<Invoice> UpdateObject(CreateOrUpdateInvoiceInput input)
        {
            Debug.Assert(input.Invoice.Id != null, "input.Invoice.Id should be set.");

            var o = await _invoicesRepository.GetAsync(input.Invoice.Id.Value);
            //Update classroom properties
            input.Invoice.MapTo(o);
            return await _invoicesRepository.UpdateAsync(o);
        }
        #endregion

        #region 根据Guid获取数据对象
        /// <summary>
        /// 新增、编辑页面中获取对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_FinanceModule_Invoices_Create, AppPermissions.Pages_FinanceModule_Invoices_Edit)]
        public async Task<GetInvoiceForEditOutput> GetObjectForEdit(NullableIdDto<Guid> input)
        {
            var output = new GetInvoiceForEditOutput
            {

            };

            if (!input.Id.HasValue)
            {
                //Creating a new object
                output.Invoice = new InvoiceEditDto();
            }
            else
            {
                //Editing an existing object
                var existingObject = await _invoicesRepository.GetAsync(input.Id.Value);

                output.Invoice = existingObject.MapTo<InvoiceEditDto>();
            }

            return output;
        }
        #endregion
    }
}
